const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const querystring = require('querystring')
const { get, set } = require('./src/db/redis')
const { access } = require('./src/utils/log')
const getCookieExpires = () => {
  const d = new Date()
  d.setTime(d.getTime() + 24 * 60 * 60 * 1000)
  // new Date(Date.now() + 24 * 60 * 60 * 1000).toGMTString()
  return d.toGMTString()
}
// session 数据
// const SESSION_DATA = {}
// 用于处理 post data
const getPostData = (req) => {
  const promise = new Promise((resolve, reject) => {
    if (req.method !== 'POST') {
      resolve({})
      return
    }
    if (req.headers['content-type'] !== 'application/json') {
      resolve({})
      return
    }
    let postData = ''
    req.on('data', (chunk) => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      if (!postData) {
        resolve({})
        return
      }
      resolve(JSON.parse(postData))
    })
  })
  return promise
}
const serverHandler = (req, res) => {
  // 记录 access log
  access(
    `${req.method} --${req.method} -- ${req.url} -- ${
      req.headers['user-agent']
    } -- ${Date.now()}`
  )

  // console.log('req原始有哪些属性', req.headers)
  // 设置返回格式
  res.setHeader('Content-Type', 'application/json')
  // 现在前端用vue搭建得项目写了代理，所以就不需要这些逻辑，非常推荐这种方式
  // 用nginx自己写代理，一会成功一会失败，不是很稳定，推荐用vue前端工程化搭建的项目自带的代理服务
  // 如果用cors允许所有域名可以跨域，登录cookie时有问题，也不推荐
  // // 允许跨域cors
  // res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8001')
  // // 允许跨域cookie
  // res.setHeader('Access-Control-Allow-Credentials', true)
  // // 允许跨域方法
  // res.setHeader(
  //   'Access-Control-Allow-Methods',
  //   'POST, GET, OPTIONS, DELETE, PUT, PATCH'
  // )
  // // 允许的请求头
  // res.setHeader(
  //   'Access-Control-Allow-Headers',
  //   'Content-Type, Authorization, X-Requested-With'
  // )
  // 处理 OPTIONS 预检请求
  // if (req.method === 'OPTIONS') {
  //   res.writeHead(200)
  //   res.end()
  //   return
  // }
  // 获取path
  const url = req.url
  req.path = url.split('?')[0]
  // 解析query
  req.query = querystring.parse(url.split('?')[1])
  // console.log('req', req.url, req.path, req.query, req.body)
  // 解析cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || ''
  cookieStr.split(';').forEach((item) => {
    if (!item) {
      return
    }
    const arr = item.split('=')
    const key = arr[0].trim()
    const val = arr[1].trim()
    req.cookie[key] = val
  })
  console.log('cookie-------', req.headers.cookie)
  // 浏览器设置的document.cookie='userid=xxxx'，req.headers.cookie根本获取不到，因为添加了httpOnly
  // 解析session
  // let needSetCookie = false
  // let userId = req.cookie.userid
  // if (userId) {
  //   if (!SESSION_DATA[userId]) {
  //     SESSION_DATA[userId] = {}
  //   }
  // } else {
  //   needSetCookie = true
  //   userId = `${Date.now()}_${Math.random()}`
  //   SESSION_DATA[userId] = {}
  // }
  // req.session = SESSION_DATA[userId]
  // console.log('session-------', SESSION_DATA, req.session)

  // 解析session（使用redis）
  let needSetCookie = false
  let userId = req.cookie.userid
  if (!userId) {
    needSetCookie = true
    userId = `${Date.now()}_${Math.random()}`
    // 初始化redis中的session值
    set(userId, {})
  }
  // 获取session
  req.sessionId = userId
  get(req.sessionId)
    .then((sessionData) => {
      if (sessionData == null) {
        // 初始化redis中的session值
        set(req.sessionId, {})
        // 设置session
        req.session = {}
      } else {
        // 设置session
        req.session = sessionData
      }
      console.log('session-------', req.session)
      return getPostData(req)
    })
    // 处理post data
    .then((postData) => {
      req.body = postData
      // 处理blog路由
      const blogResult = handleBlogRouter(req, res)
      if (blogResult) {
        blogResult.then((blogData) => {
          if (needSetCookie) {
            res.setHeader(
              'set-Cookie',
              `userid=${userId};path=/;httpOnly;expires=${getCookieExpires()}`
            )
          }
          res.end(JSON.stringify(blogData))
        })
        return
      }
      // 处理user路由
      const userResult = handleUserRouter(req, res)
      if (userResult) {
        userResult.then((userData) => {
          if (needSetCookie) {
            res.setHeader(
              'set-Cookie',
              `userid=${userId};path=/;httpOnly;expires=${getCookieExpires()}`
            )
          }
          res.end(JSON.stringify(userData))
        })
        return
      }
      // 未命中路由，返回 404
      res.writeHead(404, { 'Content-type': 'text/plain' })
      res.write('404 Not Found\n')
      res.end()
    })
}
module.exports = serverHandler
